from django.shortcuts import redirect, render, HttpResponse
from django import forms
from app01.utils.Bootstrap import BootStrapForm,BootStrapModelForm
import os
from app01 import models
def upload_list(request):
    if request.method == "GET":
        return render(request, 'upload_list.html')
    # 请求中的数据
    print(request.POST)
    # 请求发送过来的文件
    print(request.FILES)
    file_object = request.FILES.get("avatar")
    # 文件名
    print(file_object.name)
    f = open(file_object.name, mode='wb')
    for chunk in file_object.chunks():
        f.write(chunk)
    f.close()
    return HttpResponse(".......")


class UpForm(BootStrapForm):
    bootstrap_exclude_fields = ['img']
    name = forms.CharField(label="姓名")
    age = forms.IntegerField(label="年龄")
    img = forms.FileField(label="头像")


def upload_form(request):
    title = "Form上传"
    if request.method == "GET":
        form = UpForm()
        return render(request, "upload_form.html", {"form": form,"title":title})
    form = UpForm(data=request.POST,files=request.FILES)
    if form.is_valid():
        print(form.cleaned_data)
        # 读取到内容，自己处理每个字段的数据
        # 1.读取图片内容，写入到文件夹中并获取文件的路径
        image_object = form.cleaned_data.get("img")
        # file_path = "app01/static/img/{}/".format(image_object.name)
        # db_file_path = os.path.join("static","img",image_object.name)
        # file_path = os.path.join("app01",db_file_path)
        media_path = os.path.join("media",image_object.name)
        f =open(media_path,mode="wb")
        for chunk in image_object.chunks():
            f.write(chunk)
        f.close()
        # 2.将图片文件夹路径写入到数据库
        models.Boss.objects.create(
            name=form.cleaned_data['name'],
            age =form.cleaned_data['age'],
            img =media_path
        )
        return HttpResponse("1213232")

    return render(request, "upload_form.html", {"form": form,"title":title})

class UpModelForm(BootStrapModelForm):
    bootstrap_exclude_fields = ['img']
    class Meta:
        model =models.City
        fields ="__all__"

def upload_model_form(request):
    """上传文件和数据"""
    title= "ModelForm上传文件"
    if request.method =="GET":
        form = UpModelForm()
        return render(request, 'upload_model_form.html', {"form": form, "title": title})
    form = UpModelForm(data=request.POST,files =request.FILES)
    if form.is_valid():
        form.save()
        return HttpResponse("成功")
    return render(request,'upload_model_form.html',{"form":form,"title":title})
